import axios from 'axios';

// 创建axios实例
const api = axios.create({
  baseURL: '/vehicle-secure',
  headers: {
    'Content-Type': 'application/json'
  }
});

// 添加请求拦截器
export const setupAuthInterceptor = () => {
  const requestInterceptor = api.interceptors.request.use(
    (config) => {
      // 从localStorage获取token
      const token = localStorage.getItem('token');
      
      // 如果token存在，将其添加到请求头
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }
      
      return config;
    },
    (error) => {
      return Promise.reject(error);
    }
  );

  return () => {
    api.interceptors.request.eject(requestInterceptor);
  };
};

// 添加响应拦截器
export const setupResponseInterceptor = (navigate) => {
  const responseInterceptor = api.interceptors.response.use(
    (response) => {
      return response;
    },
    (error) => {
      // 在开发环境下，对API请求失败不做严格处理
      if (process.env.NODE_ENV === 'development') {
        console.log('API request failed in development mode:', error.message);
        // 开发环境下，即使遇到401错误也不清除token和重定向，以便继续使用应用
        // 仅在控制台显示错误信息
        return Promise.reject(error);
      } else {
        // 生产环境下正常处理401未授权错误
        if (error.response?.status === 401) {
          // 清除存储的token
          localStorage.removeItem('token');
          // 重定向到登录页面
          navigate('/login');
        }
        return Promise.reject(error);
      }
    }
  );

  return () => {
    api.interceptors.response.eject(responseInterceptor);
  };
};

// API请求方法封装
export const apiRequest = {
  get: async (url, params = {}) => {
    return await api.get(url, { params });
  },
  
  post: async (url, data = {}) => {
    return await api.post(url, data);
  },
  
  put: async (url, data = {}) => {
    return await api.put(url, data);
  },
  
  delete: async (url) => {
    return await api.delete(url);
  }
};

export default api;